<template>
  <div id="AddActivity">
    <main-header :title="headTitle" :crumbsArr="crumbsArr" />
    <div class="main_wrapper" >
      <div class="main">
        <el-form :model="addForm" status-icon :rules="addFormRules" ref="addForm" label-width="100px">
          <el-form-item label="活动名称" prop="title">
            <el-input type="text" v-model="addForm.title"></el-input>
          </el-form-item>
          <el-form-item label="活动详情" prop="pic">
            <input
              ref="addPicInput"
              type="file" name="itemFile"
              style="display: none;"
              accept="image/*"
              @change="addPicInputChange('addPicInput')">
            <el-input style="display: none;" type="text" v-model="addForm.pic"></el-input>
            <div class="pic_block" v-if="addForm.pic">
              <img
                width="284px" height="146px" alt=""
                :src="`${addForm.pic}?imageView2/1/w/284/h/146`">
              <div class="hover_delete">
                <el-button
                  type="danger" icon="el-icon-delete" circle
                  @click="deletePic">
                </el-button>
              </div>
            </div>
            <el-button
              v-if="!addForm.pic"
              class="add_pic_btn"
              @click="clickAddImg('addPicInput')"
              v-loading="addPicLoading"
            >
              <i class="el-icon-plus"></i>
            </el-button>
          </el-form-item>
          <el-form-item label="关联商品" prop="itemId">
            <el-input type="text" v-model.number="addForm.itemId"></el-input>
          </el-form-item>
          <el-form-item label="链接文字" prop="linktext">
            <el-input v-model="addForm.linktext"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitBtnClick('addForm')">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <el-dialog
      title="提示"
      :visible.sync="submitVis"
      width="30%"
    >
      <span>确认提交？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="() => { resetAddFrom(); submitVis = false }">取 消</el-button>
        <el-button type="primary" @click="submitOk" :loading="submitloading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as qiniu from 'qiniu-js'
import API from '@/config/api.js'
import ErrorConfig from '@/config/error.config.js'
import MainHeader from '@/components/layouts/MainHeader'
export default {
  name: 'AddTicket',
  data () {
    return {
      crumbsArr: [ // 面包屑
        { name: 'welcome', txt: '首页' }, { name: 'activity', txt: '活动管理' }, { txt: '添加活动' }
      ],
      headTitle: '添加活动',
      addFormRules: {
        title: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        pic: [
          { required: true, message: '请添加图片', trigger: 'change' }
        ],
        itemId: [
          { required: true, message: '请输入关联商品ID', trigger: 'blur' },
          { type: 'number', message: '商品ID为数字', trigger: 'blur' }
        ],
        linktext: [
          { required: true, message: '请输入链接文字', trigger: 'blur' }
        ]
      },
      addForm: {
        title: '',
        pic: '',
        itemId: '',
        linktext: ''
      },
      addPicLoading: false,
      submitVis: false,
      submitloading: false
    }
  },
  // beforeRouteEnter (to, from, next) {
  //   next(vm => vm.)
  // },
  watch: {
    '$route' (to, from) {
      // let arr = this.crumbsArr
      // if (to.name === 'ticket_add') {
      //   arr[arr.length - 1].txt = '奖券新增'
      // }
      // if (to.name === 'ticket_edit') {
      //   arr[arr.length - 1].txt = '奖券编辑'
      // }
      // this.crumbsArr = Object.assign([], arr)
    }
  },
  components: {
    MainHeader
  },
  methods: {
    clickAddImg (fileInput) { // 模拟点击file input
      this.$refs[fileInput].click()
    },
    async addPicInputChange (fileInput) { // 添加图片
      this.addPicLoading = true
      const response = await API.getQiNiuToken()
      const qiniuConfig = { // 七牛云上传参数
        file: this.$refs[fileInput].files[0],
        key: new Date().getTime(),
        token: response.data,
        putExtra: {
          fname: '',
          params: {},
          mimeType: [] || null
        },
        config: {
          useCdnDomain: true
        }
      }

      // 注入七牛参数
      let observable =
        qiniu.upload(qiniuConfig.file, qiniuConfig.key, qiniuConfig.token, qiniuConfig.putExtra, qiniuConfig.config)

      // 开始上传
      observable.subscribe(undefined, (errmsg) => {
        this.addPicLoading = false
        this.$message.error('图片上传失败，请重试')
      }, async (res) => {
        this.addForm.pic = `${API.FILE_HOST_URL}${res.key}`
        this.addPicLoading = false
        // const resData = await API.getDownloadUrl(`${API.FILE_HOST_URL}${res.key}`)
        // if (resData.code === 1) {
        //   this.addForm.pic = resData.data
        // } else {
        //   this.$message.error(ErrorConfig[resData.code])
        // }
        // this.addPicLoading = false
      })
    },
    deletePic () { // 删除图片
      this.addForm.pic = ''
    },
    submitBtnClick (formName) { // 提交按钮点击
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitVis = true
        } else {
          return false
        }
      })
    },
    async submitOk () { // 提交表单
      this.submitloading = true
      const response = await API.addActivity(this.addForm)
      const { code } = response
      this.submitloading = false
      this.submitVis = false
      if (code === 1) {
        this.resetAddFrom()
        // 跳转到活动管理页面
        this.$router.push({ name: 'activity' })
      } else {
        if (code === -1) {
          const { msg } = response
          this.$message.error(msg)
        } else {
          this.$message.error(ErrorConfig[code])
        }
      }
    },
    resetAddFrom (formName = 'addForm') { // 重置表单
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style scoped lang="scss">
  #AddActivity {
    .main_wrapper {
      padding: 20px 20px 0;
      .main {
        box-sizing: border-box;
        padding: 20px;
        border-radius: 4px;
        background: #fff;
        .el-form {
          .el-form-item {
            &:not(:last-child) {
              width: 60%;
            }
            &:last-child {
              text-align: right;
            }
          }
          .pic_block {
            position: relative;
            width: 284px;
            height: 146px;
            &:hover {
              .hover_delete {
                display: block;
              }
            }
            .hover_delete {
              display: none;
              position: absolute;
              top: 0;
              right: 0;
              bottom: 0;
              left: 0;
              background: rgba(0, 0, 0, .3);
              .el-button {
                position: absolute;
                top: 50%;
                left: 50%;
                -webkit-transform: translate(-50%, -50%);
                -moz-transform: translate(-50%, -50%);
                -ms-transform: translate(-50%, -50%);
                -o-transform: translate(-50%, -50%);
                transform: translate(-50%, -50%);
              }
            }
          }
          .add_pic_btn {
            width: 284px;
            height: 146px;
            i {
              font-size: 20px;
            }
          }
        }
      }
    }
  }
</style>
